require( "tmysql" )

if !tmysql then
	return
end

local InsertId

tmysql.query( "INSERT INTO `sf_log_game`(`map`) VALUES (\"" .. game.GetMap() .. "\")", function( res, status, err )
	if status != 1 then
		Error( err )
	end
	
	//The insert id is stored in the err value
	InsertId = err

end, 2 )

local function checkError( res, status, err )
	if status != 1 then
		Error( err )
	end
end

local DeathToAdd = {}

local function DumpDeaths()
	
	local InsertValues = {}
	
	for _, Item in pairs( DeathToAdd ) do
		
		table.insert( InsertValues, "(".. 
			Item.Player .. "," ..
			Item.Killer .. "," ..
			Item.PlayerX .. "," ..
			Item.PlayerY .. "," ..
			Item.KillerX .. "," ..
			Item.KillerY .. "," ..
			Item.GameTime .. "," ..
			Item.Weapon .. "," ..
			Item.GameId..")" )
		
	end
	
	DeathToAdd = {}
	
	tmysql.query( "INSERT INTO `sf_log_kills`(`victim_id` ,`killer_id` ,`victim_x` ,`victim_y` ,`killer_x` ,`killer_y`,`gametime` ,`weapon`,`game_id`)"
		.. " VALUES " .. table.concat(InsertValues,","), checkError )
	
end

hook.Add( "PlayerDeath", "logDeath", function( ply, inflictor, killer )

	if ValidPlayer( ply ) then
	
		local Item = {
			Killer = 0,
			KillerX = 0,
			KillerY = 0,
			Weapon = "NULL"
		}
		local plyPos = ply:GetPos()
		
		Item.Player = ply:SQLId()
		Item.PlayerX = plyPos.x
		Item.PlayerY = plyPos.y
		Item.GameTime = math.floor( CurTime() )
		Item.GameId = InsertId
		
		if ValidEntity( killer ) then
			local KillerPos = killer:GetPos()
			
			if ValidPlayer( killer ) then
				Item.Killer = killer:SQLId()
			end
			
			Item.KillerX = KillerPos.x
			Item.KillerY = KillerPos.y
		end
		
		if ValidEntity( inflictor ) then
			Item.Weapon = "\"" .. inflictor:GetClass() .. "\""
		end
		
		table.insert( DeathToAdd, Item )
	
	end
	
	if #DeathToAdd > 20 then
		DumpDeaths()
	end

end )

hook.Add( "ShutDown", "DumpLog", DumpDeaths )
 


